const fs = require('fs')
const path = require('path')

const renderFile = (filePath, obj, cb) => {
    fs.readFile(filePath, 'utf8', function (err, html) {
        if (err) {
            return cb(err, html)
        }

        html = html.replace(/\{\{([^}]+)\}\}/g, function () {
            let key = arguments[1].trim()
            return '${' + key + '}'
        })

        let head = `let str = '';\r\n with(obj){\r\n`
        head += 'str+=`'
        html = html.replace(/\{\%([^%]+)\%\}/g, function () {
            return '`\r\n' + arguments[1] + '\r\nstr+=`\r\n'
        })
        let tail = '`}\r\n return str;'
        let fn = new Function('obj', head + html + tail)
        cb(err, fn(obj))
    })
}

renderFile(path.resolve('assets', 'template.html'), { name: '小A', age: 16, arr: [1, 2, 3] }, function (err, data) {
    console.log(data)
})
